import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

interface User {
  id: number;
  name: string;
  phoneNumber: string;
}

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null);
  const token = ref<string | null>(localStorage.getItem('authToken'));

  const isLoggedIn = computed(() => !!user.value && !!token.value);

  function setCredentials(userData: User, authToken: string) {
    user.value = userData;
    token.value = authToken;
    localStorage.setItem('authToken', authToken);
    localStorage.setItem('authUser', JSON.stringify(userData));
  }

  function clearCredentials() {
    user.value = null;
    token.value = null;
    localStorage.removeItem('authToken');
    localStorage.removeItem('authUser');
  }
  
  function initStore() {
    const storedToken = localStorage.getItem('authToken');
    const storedUser = localStorage.getItem('authUser');
    if (storedToken && storedUser) {
      token.value = storedToken;
      try {
        user.value = JSON.parse(storedUser);
      } catch (e) {
        console.error('Failed to parse user data from localStorage', e);
        clearCredentials();
      }
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    setCredentials,
    clearCredentials,
    initStore,
  };
}); 